import bottle
from bottle import run, route, request, HTTPError, HTTPResponse, redirect, response

from pymongo import errors as DatabaseErrors

import os
import json
import ConfigParser

from RBS import Config

from system import Database

import datetime

configuration = None

dbconn = None

def doesPackageExist(packageName):
    pass

@route('/')
def index():
    #try:
    #    #c = Database.Connection(configuration.getConfiguration('rbs')['dbtype'], server=configuration.getConfiguration('rbs')['dbserver'], db=configuration.getConfiguration('rbs')['dbname'])
    #    d = Database.Connection("mongodb", server="192.168.0.20")
    #    
    #except DatabaseErrors.ConnectionFailure, e:
    #    return HTTPError(500, "Problem connecting to database, dude: %s" % e)
    
    return "<h2>%s</h2><p>Your address is: %s</br><p>Your conn is: %s</br>" % (configuration.getConfiguration('rbs')['title'], request['REMOTE_ADDR'], db.dbserver)

@route('/build')
def rpmbuild():
    buildOptions = {}
    
    # Store HTTP GET arguments
    buildOptions['package'] = request.GET.get('package', default=None)
    #buildOptions['action'] = request.GET.get('action', default=None)
    
    buildOptions['ostype'] = request.GET.get('ostype', default=None)
    
    buildOptions['submittime'] = datetime.datetime.now()
    
    httpAcceptType = request.environ.get('HTTP_ACCEPT')
    
    #if (buildOptions['package'] <> None and buildOptions['action'] <> None) and httpAcceptType in ['application/json']:
    #    return json.dump(buildOptions)
    #else:
    #    return HTTPError(status='500', body="Unsupported Type for this service, dumbshit.  Try again.")
    
    # If any build options are None, return '500'
    for buildopt, value in buildOptions.iteritems():
        if value == None:
            #return HTTPError(500, "Darn!  Your build service request was incomplete for required build option '%s'" % buildopt)
            return json.dumps({'rc': ''})
    
    # Let's insert this into our queue
    queue = dbconn.db['queue']
    
    queue.insert
    
    
    #return HTTPError(500, "Unsupported type for this service, juicebag.  Try again.")
    response.set_header('Content-Type', 'application/json')
    return json.dumps(buildOptions)
    
    #if httpAcceptType == "applicatoin/json":
    #    return json.dumps(
    #        {'package': packageName,
    #        'action': queryAction,
    #        'acceptType': request.environ.get('HTTP_ACCEPT') }
    #    )

@route('/query')
def rpmquery():
    packageName = request.GET.get('package', default=None)

@route('/config')
def rbsconfig():
    section = request.GET.get('section', default=None)
    configReload = request.GET.get('reload', default=None)
    
    if section <> None:
        if section in configuration.parserConfig.sections():
            response.set_header('Content-Type', 'application/json')
            return json.dumps(configuration.getConfiguration(section))
        else:
            return HTTPError(500, "'" + section + "' is not a valid option.  What were you thinking?")

    if configReload <> None:
        try:
           configuration.loadConfiguration()
           return HTTPResponse(body="Success", status=200)
           #redirect("http://localhost:8081", code=200)
        except Exception, e:
            return HTTPError(500, "Darn! Had a problem reloading configuration: %s" % e)

def main():
    # Read in config
    for f in ['/home/adosch/code/python/rbs','/tmp']:
        f += "/rbs.cfg"
        
        if os.path.isfile(f):
            if os.access(f, os.R_OK):
                
                global configuration
                configuration = RBSConfig(f)
                
                try:
                    configuration.loadConfiguration()
                except:
                    return HTTPError(500, "Aww, man!  Error trying to parse/load the configuration file.")
                
                break
    
    # If parserConfig is still None, then we didn't find one.  Get the hell out!
    if configuration == None:
        return HTTPError(500, "No configuration file to load!  You may want to do that before starting this service up, genius.")

    # Display traceback
    bottle.debug(True)
   
    # Create database connection
    try:
        #c = Database.Connection(configuration.getConfiguration('rbs')['dbtype'], server=configuration.getConfiguration('rbs')['dbserver'], db=configuration.getConfiguration('rbs')['dbname'])
        #d = Database.Connection("mongodb", server="192.168.0.20")
        global dbconn
        dbconn = Database.Connection("mongodb", server=configuration.getConfiguration('rbs')['dbserver'])
        
    except DatabaseErrors.ConnectionFailure, e:
        return HTTPError(500, "Problem connecting to database, dude: %s" % e)
    
    # Start it up!
    run(host='localhost', port=8081, reloader=True)

if __name__ == '__main__':
    main()

